package com.example.mq.mqserver.core;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.Data;

import java.util.HashMap;
import java.util.Map;

@Data
public class Exchange {
    //使用name作为交换机的唯一身份标识
    private String name;
    //交换机类型DIRECT FANOUT TOPIC
    private ExchangeType type = ExchangeType.DIRECT;
    //该交换机是否需要持久化存储
    private boolean durable = false;
    //Todo: 如果当前交换机没人使用 就自动删除
    private boolean autoDelete = false;
    //Todo: 额外参数选项
    //为了将这个数据存储到数据库中 要转换为json字符串存储
    private Map<String , Object> arguments  = new HashMap<>();

    public String getArguments(){
        //把当前arguments参数从map转化为json字符串
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            return objectMapper.writeValueAsString(arguments);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        //如果异常 返回空json字符串
        return "{}";
    }

    public void setArguments(String argumentsJson){
        //吧argumentsJson转化为map对象
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            objectMapper.readValue(argumentsJson,new TypeReference<HashMap<String,Object>>(){});
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
    }

    //针对arguments 再提供一组getter setter方法 在代码内部测试使用
    public Object getArguments(String key){
        return arguments.get(key);
    }

    public void setArguments(String key, Object value){
        arguments.put(key,value);
    }

    public void setArguments(Map<String,Object> arguments){
        this.arguments = arguments;
    }

}
